package com.App.controller;

import com.App.pojo.Result;
import com.App.pojo.Student;
import com.App.service.StudentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/student")
//@CrossOrigin
public class StudentController {

    @Autowired
    StudentService studentService;

    @DeleteMapping("/{id}")   /*删除学生信息*/
    public Result<?> del(@PathVariable Integer id){
        boolean result = studentService.removeById(id);
        if(result){
            return Result.success();
        }
        return Result.error("删除id为"+id+"学生失败!");
    }

    @PutMapping  /*修改学生信息*/
    public Result<?> update(@RequestBody Student student){
        boolean result = studentService.updateById(student);
        if(result){
            return Result.success();
        }
        return Result.error("修改id为"+student.getId()+"学生失败!");
    }

    @PostMapping   /*添加学生信息*/
    public Result<?> add(@RequestBody Student student){
        boolean result = studentService.save(student);
        if(result){
            return Result.success();
        }
        return Result.error("添加学生失败!");
    }

    @GetMapping  /*分页查询和模糊查询*/
    public Result<?> list(@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "5") Integer pageSize, String studentName){
//        List<Student> studentList = studentService.list();
//        return Result.success(studentList);
//        Page<Student> page = studentService.page(new Page(pageNum,pageSize), Wrappers.<Student>lambdaQuery().like(Student::getStudentname,studentName));
//        return Result.success(page);
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!ObjectUtils.isEmpty(studentName), Student::getStudentname, studentName);  /*根据关键字进行模糊查询*/
        Page<Student> page = studentService.page(Page.of(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }
}
